<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\Validate;
use think\cache\driver\Redis;

/**
 * Order控制器
 */
class Order extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Order();

        $this->validate = \app\admin\validate\Order::class;
    }


    /**
     * 列表
     */
    public function index()
    {
        $limits = $this->request->get('limit', 10);
        $page = $this->request->get('page', 1);
        $newpage = $page - 1;
        if ($newpage == 0) {
            $limit1 = 0;
            $limit2 = $limits;
        } else {
            $limit1 = $newpage * $limits;
            $limit2 = $limits;
        }
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $where2 = array();
        if (!empty($filters['name'])) {
            $where2[] = array('a.name', 'LIKE', '%' . trim($filters['name']) . '%');
        }
        if (!empty($filters['site_id'])) {
            $where2[]  = ['a.site_id', '=', $filters['site_id']];
        }
        if (!empty($filters['shipping_name'])) {
            $where2[] = array('a.shipping_name', 'LIKE', '%' . $filters['shipping_name'] . '%');
        }
        if (!empty($filters['tracking_number'])) {
            $where2[] = array('a.tracking_number', 'LIKE', '%' . $filters['tracking_number'] . '%');
        }
        if (!empty($filters['email'])) {
            $where2[] = array('a.email', 'LIKE', '%' . $filters['email'] . '%');
        }
        if (!empty($filters['sku'])) {
            $where2[] = array('c.sku', 'LIKE', '%' . $filters['sku'] . '%');
        }
        if (!empty($filters['financial_status'])) {
            $filters['financial_status'] = $this->financial_status_switch($filters['financial_status']);
            $where2[]  = ['a.financial_status', '=', $filters['financial_status']];
        }

        if (!empty($filters['created_at'])) {
            $where2[]  = ['a.created_at', '>=', strtotime($filters['created_at'][0])];
            $where2[]  = ['a.created_at', '<=', strtotime($filters['created_at'][1])];
        }
        // halt($where2);
        if (empty($where2) && $page == 1 && $limits == 10) {
            $redis = new Redis();
            $lists = $redis->get('lists_order');
            if (empty($lists)) {
                $where3[] = ['c.sku', '>', 0];
                $lists = table('order')
                    ->alias('a')
                    ->field('a.id,a.name,a.email,a.shipping_name,b.variant_title,a.tracking_number,a.total_price,a.fulfillment_status,a.created_at,a.site_id,a.financial_status,c.sku,b.quantity,a.updatetime,a.is_mark')
                    ->join('qu_order_quantity b', 'a.id = b.order_id', 'left')
                    ->join('qu_order_sku c', 'b.variant_id = c.variants_id', 'left')
                    ->where($where2)
                    ->where($where3)
                    ->group('a.id')
                    ->order('a.created_at desc')
                    ->limit($limit1, $limit2)
                    ->select()->toarray();
                foreach ($lists as $k => $v) {
                    $site = table('site')
                        ->where(['id' => $v['site_id']])->find();
                    if (!empty($site)) {
                        $lists[$k]['site_name'] = $site['site_name'];
                    } else {
                        $lists[$k]['site_name'] = '未知';
                    }
                    $lists[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
                    $lists[$k]['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
                    $lists[$k]['financial_status'] = $this->financial_status_switch($v['financial_status']);
                    $lists[$k]['fulfillment_status'] = $this->fulfillment_status_switch($v['fulfillment_status']);
                }
                $redis->set('lists_order', $lists, 60 * 5);
            }
        } else {
            $where3[] = ['c.sku', '>', 0];
            $lists = table('order')
                ->alias('a')
                ->field('a.id,a.name,a.email,a.shipping_name,b.variant_title,a.tracking_number,a.total_price,a.fulfillment_status,a.created_at,a.site_id,a.financial_status,c.sku,b.quantity,a.updatetime,a.is_mark')
                ->join('qu_order_quantity b', 'a.id = b.order_id', 'left')
                ->join('qu_order_sku c', 'b.variant_id = c.variants_id', 'left')
                ->where($where2)
                ->where($where3)
                ->group('a.id')
                ->order('a.created_at desc')
                ->limit($limit1, $limit2)
                ->select()->toarray();
            foreach ($lists as $k => $v) {
                $site = table('site')
                    ->where(['id' => $v['site_id']])->find();
                if (!empty($site)) {
                    $lists[$k]['site_name'] = $site['site_name'];
                } else {
                    $lists[$k]['site_name'] = '未知';
                }
                $lists[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
                $lists[$k]['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
                $lists[$k]['financial_status'] = $this->financial_status_switch($v['financial_status']);
                $lists[$k]['fulfillment_status'] = $this->fulfillment_status_switch($v['fulfillment_status']);
            }
        }

        $where3[] = ['c.sku', '>', 0];
        $count = table('order')
            ->alias('a')
            ->join('qu_order_quantity b', 'a.id = b.order_id', 'left')
            ->join('qu_order_sku c', 'b.variant_id = c.variants_id', 'left')
            ->where($where2)
            ->where($where3)
            ->group('a.id')
            ->count();

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => (int)$count,
            'data' => $lists,
        ];

        return json($data);
    }


    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $one_kfs = !empty($post['one_kfs']) ? $post['one_kfs'] : [];
            $order_id = !empty($post['id']) ? $post['id'] : [];
            $email_detail = !empty($post['email_detail']) ? $post['email_detail'] : '';
            // halt($one_kfs);
            // $kfdetail_num = table('kfdetail')->where(['orderid' => $order_id])->count();
            foreach ($one_kfs as   $v) {
                //通过订单号查询当前数据表是否有数据
                $kfdetail_num = table('kfdetail')->where(['orderid' => $order_id, 'tid' => $v[0], 'did' => $v[1]])->count();
                if ($kfdetail_num == 0) {
                    //插入数据
                    table('kfdetail')->insert(['tid' => $v[0], 'did' => $v[1], 'orderid' => $order_id]);
                } else {
                    table('kfdetail')->where(['orderid' => $order_id, 'tid' => $v[0], 'did' => $v[1]])->update(['tid' => $v[0], 'did' => $v[1]]);
                }
            }
            //更新标记状态
            table('order')->where(['id' => $order_id])->update(['is_mark' => 1, 'mark_time' => time(), 'email_detail' => $email_detail]);
            return success('操作成功！');
        }
        $rst = [];
        //查询qustion类型表
        if (empty($row)) {
            return error('数据不存在');
        }
        $row = $row->toarray();
        //返回对应数组即可
        $kf_detail = table('kfdetail')->where(['orderid' => $row['id']])->select()->toarray();
        $optids = [];
        foreach ($kf_detail as  $v) {
            $optids[] = [$v['tid'], $v['did']];
        }
        $row['optionsid'] = $optids;
        $qustion = table('qustiontype')->select()->toarray();
        //查询qustion详情表
        foreach ($qustion as $v) {
            $qustiondetail = table('qustiondetail')->field('id as value,title as label')->where(['pid' => $v['id']])->select()->toarray();
            $rst[] = [
                'value' => $v['id'],
                'label' => $v['title'],
                'children' => $qustiondetail,
            ];
        }

        $row['options'] = $rst;
        // halt($row);
        return success('ok', $row);
    }
    /**
     * 支付状态
     * @param array params
     */
    public function financial_status_switch($status)
    {
        switch ($status) {
            case '1':
                $status = 'paid';
                break;
            case '2':
                $status = 'partially_paid';
                break;
            case '3':
                $status = 'partially_refunded';
                break;
            case '4':
                $status = 'refunded';
                break;

            case 'paid':
                $status = '已支付';
                break;
            case 'partially_paid':
                $status = '部分支付';
                break;
            case 'partially_refunded':
                $status = '部分退款';
                break;
            case 'refunded':
                $status = '退款';
                break;
            default:
                $status = '';
        }
        return $status;
    }



    /**
     * 物流状态
     * @param array params
     */
    public function fulfillment_status_switch($status)
    {
        switch ($status) {
            case '1':
                $status = 'fulfilled';
                break;
            case '2':
                $status = 'partial';
                break;
            case '3':
                $status = 'restocked';
                break;
            case '4':
                $status = 'unshipped';
                break;

            case 'fulfilled':
                $status = '已发货';
                break;
            case 'partial':
                $status = '部分发货';
                break;
            case 'restocked':
                $status = '重新补货';
                break;
            case 'unshipped':
                $status = '未发货';
                break;
            default:
                $status = '';
        }
        return $status;
    }
}
